<?php
/**
 * 文章类
 * @author zengnz
 *
 */
class ArticleAction extends CommonAction
{
	/**
	 * 文章类别
	 */
	public function articleCategory(){
		$Model = M('article_category');
		
		$this -> _list( $Model, '', true, array('table'=>'ASC', 'pid'=>'ASC', 'id'=>'DESC') );
		
		$this -> display();
	}
	
	/**
	 * 添加文章类别
	 */
	public function articleCategoryAdd() {
		if ($_POST) {
			$Model = D('article_category');
			if (false === $Model -> create ()) {
				$this -> alertError( $Model -> getError () );
			}
			
			$this -> insertExt($Model);
			$this -> insertCheck($Model);
			
			$ret = $Model -> add();
			if (!$ret)
				$this -> alertError('添加记录失败！');
			else {
				D('Log') -> actionLog(LogModel::ADD, '添加文章类别记录！');
				$this -> success('添加记录成功！');
			}
		} else {
			$categorys = array(array('id'=>0, 'name'=>'一级类别'));
			$parentCategory = D('ArticleCategory') -> field('id, name') -> where('pid = 0') -> select();
			if ($parentCategory)
				$categorys = array_merge($categorys, $parentCategory);
			
			$this -> assign('parentCategory', $categorys);
			$this -> display();
		}
			
	}
	
	/**
	 * 扩展字段
	 * @see CommonAction::insertExt()
	 */
	protected function insertExt($Model) {
		$Model -> mark = strtoupper($Model -> mark);
		$Model -> url = ucfirst($Model -> url);
		$Model -> table = strtolower($Model -> table);
		$Model -> create_time = time();
		$Model -> create_by = $this->getLoginId();
		
		if (isset($Model -> sign))
			$Model -> sign = 1;
	}
	
	/**
	 * 删除文章类别
	 */
	public function deleteCategory() {
		$id = $this -> _get('id');
		if (!$id)
			$this -> alertError('参数错误！');
		
		$Model = M('article_category');
		if(empty($Model))
			$this -> alertError('模型对象不存在！');
		
		$sql = 'id='.$id;
		$ret = $Model -> where($sql) -> delete();
		if (!$ret)
			$this -> alertError($Model -> getError());
		else {
			D('Log') -> actionLog(LogModel::DEL, '删除文章类别表相关记录！');
			$this -> success('删除成功！');
		}
		
	}
	
	/**
	 * 添加文章
	 */
	public function articleAdd() {
		$tableName = trim($this -> _get('table'));
		if (!$tableName)
			$this -> alertError('参数错误！');
		
		if ( $_POST ) {
			$category_id = intval( $_POST['category_id'] );
			$title = trim( $_POST['title'] );
			$desc = trim($_POST['desc']);
			$content = $_POST['content'];
			//图片路径
			$filePath = trim($_POST['img_path']);
			$path = '';
			if ($filePath)
				$path = formatStr($filePath, '|', '/upload', '|', 'Public/upload');
			
			//特殊字符转义
			$title = htmlspecialchars($title);
			$desc = htmlspecialchars($desc);
			
			if ( !isset($title) || $category_id == 0 )
				$this -> alertError('类别所属非法！');
			//字段合法验证
			if ( !$title || !$desc || !$content )
				$this -> alertError('所有字段均为必填，请填写完整！');
			
			
			$articleTable = 'article_'.$tableName;
			$Model = D($articleTable);
			
			$sql = 'category_id='.$category_id.' and title="'.$title.'"';
			$record = $Model -> field('id') -> where($sql) -> find();
			if ($record)
				$this -> alertError('该类别下已存在相同的文章标题！');
			
			$data = array(
					'category_id' 	=> $category_id,
					'title'		  	=> $title,
					'desc'		  	=> $desc,
					'content'	  	=> $content,
					'images'		=> $filePath,
					'creator_type' 	=> 1,
					'creator_id'	=> $this -> getLoginId(),
					'create_time' 	=> time(),
					'creator' 	  	=> $this -> getAccount(),
					'status'		=> 1	
			);
			
			$ret = $Model -> add( $data );
			if (!$ret)
				$this -> alertError('添加文章失败！');
			else
				$this -> success('添加文章成功！');		
				
		} else {
			//获取相关类别
			$categoryList = D('Article', 'Logic') -> getSubCategory($tableName);
			
			$categoryList = array_merge( array(array('id'=>'', 'name'=>'--请选择--')), $categoryList );
			
			$this -> assign('categorys', $categoryList);
			$this -> assign('table', $tableName);
			
			$this -> display();
		}
		
		
	}
	
	
	/**
	 * 更新文章
	 */
	public function articleUpdate() {
		$tableName = trim($this -> _get('table'));
		$id = intval($this -> _get('id'));
		
		if ( $_POST ) {
			$id = intval($_POST['id']);
			if (!$tableName || !$id)
				$this -> alertError('参数错误！');
			$category_id = intval( $_POST['category_id'] );
			$title = trim( $_POST['title'] );
			$desc = trim($_POST['desc']);
			$content = $_POST['content'];
			//图片路径
			$filePath = trim($_POST['img_path']);
			$path = '';
			if ($filePath)
				$path = formatStr($filePath, '|', '/upload', '|', 'Public/upload');
				
			//特殊字符转义
			$title = htmlspecialchars($title);
			$desc = htmlspecialchars($desc);
				
			if ( !isset($title) || $category_id == 0 )
				$this -> alertError('类别所属非法！');
			//字段合法验证
			if ( !$title || !$desc || !$content )
				$this -> alertError('所有字段均为必填，请填写完整！');
				
			$Model = new Model();
			$articleTable = 'article_'.$tableName;
			$imageTable = 'article_'.$tableName.'_image';
				
			$sql = 'category_id='.$category_id.' AND title="'.$title.'" AND id !='.$id;
			$record = $Model -> table($articleTable) -> field('id') -> where($sql) -> find();
			if ($record)
				$this -> alertError('该类别下已存在相同的文章标题');
				
			$data = array(
					'category_id' => $category_id,
					'title'		  => $title,
					'desc'		  => $desc,
					'content'	  => $content,
					'update_time' => time(),
			);
				
			//事务开始
			$Model -> startTrans();
			$ret = $Model -> table($articleTable) -> where('id='.$id)
				-> data($data)
				-> save();
			
			if ($ret) {
				if (!empty($path)) {
					$sql = 'article_id='.$id;
					$oldPath = $Model -> table($imageTable) -> where($sql) -> find();
					if ($oldPath) {
						$path .= '|' . $oldPath['images'];
						$imgRet = $Model -> table($imageTable) -> where($sql) -> data(array('images'=>$path)) -> save();
					} else {
						$imgRet = $Model -> table($imageTable) -> add(array('article_id'=>$id, 'images'=>$path));
					}
					
					if (!$imgRet) {
						$Model -> rollback();
						$this -> alertError('更新文章图片路径失败');
					}
				}
				
				$Model -> commit();
				//记录日志
				D('Log') -> actionLog(LogModel::UPDATE, '更新文章，文章类别：'.$tableName.'，文章ID：'.$id);
				$this -> success('更新文章成功！');
			} else {
				$Model -> rollback();
				$this -> alertError('更新文章内容失败！');
			}
				
		} else {
			if (!$tableName || !$id) 
				$this -> alertError('参数错误！');
			
			$record = $this -> getArticleById($id, 'article_'.$tableName);
			if (!$record)
				$this -> alertError('记录不存在或者已经被删除！');
			//获取相关类别
			$categoryList = D('Article', 'Logic') -> getSubCategory($tableName);
			$list = array();
			if ($categoryList) {
				foreach ($categoryList as $key => $val) {
					$list[$val['id']] = $val;
				}
			}
				
			$list = array_merge( array(array('id'=>'', 'name'=>'--请选择--')), $list );
			
			$this -> assign('record', $record);
			$this -> assign('categorys', $list);
			$this -> assign('table', $tableName);
				
			$this -> display();
		}
	}
	
	/**
	 * 删除记录
	 */
	public function delete() {
		$tableName = trim($this -> _get('table'));
		$id = intval($this -> _get('id'));
		if (!$id || !$tableName)
			$this -> alertError('参数错误！');
	
		$Model = new Model();
		$articleTable = 'article_'.$tableName;
		$imageTable = 'article_'.$tableName.'_image';
		
		$Model -> startTrans();
		
		$articleRet = $Model -> table($articleTable) -> where('id='.$id) -> delete();
		if ($articleRet) {
			//如果有相关图片记录，删除图片信息保存记录，并删除图片
			$imageRecord = $Model -> table($imageTable) -> where('article_id='.$id) -> find(); 
			$imageRet = 1; //初始化成功
			if ($imageRecord) {
				$imageRet = $Model -> table($imageTable) -> where('article_id='.$id) -> delete();
				if ($imageRet)
					delImages($imageRecord['images']);
				else
					$imageRet = 0;
			}
			
			if ($imageRet) {
				$Model -> commit();
				//记录日志
				D('Log') -> actionLog(LogModel::DEL, '删除'.$tableName.'相关记录！记录id：'.$id);
				$this -> success('删除文章记录成功');
			} else {
				$Model -> rollback();
				$this -> alertError('删除文章相关的图片记录失败！');
			}
			
		} else {
			$this -> alertError('删除文章记录失败！');
		}
	
	}
	
	
	/**
	 * 文章预览
	 */
	public function articleView() {
		$tableName = trim($this -> _get('table'));
		$id = intval($this -> _get('id'));
		
		if (!$tableName || !$id)
			$this -> alertError('参数错误！');
		
		$record = $this -> getArticleById($id, 'article_'.$tableName);
		if (!$record)
			$this -> alertError('文章记录不存在或者已经被删除！');
		
		$this -> assign('record', $record);
		$this -> display();
	}
	
	/**
	 * 生活相关列表
	 */
	public function live() {
		$Model = M('article_live');
		
		$this -> _list( $Model, array(), true );
		
		$this -> display();
	}
	
	/**
	 * 知识相关
	 */
	public function knowledge() {
		$Model = M('article_knowledge');
		
		$this -> _list( $Model, array(), true );
		
		$this -> display();
	}
	
	/**
	 * 财经
	 */
	public function economic() {
		$Model = M('article_economic');
		
		$this -> _list( $Model, array(), true );
		
		$this -> display();
	}
	
	/**
	 * 电子产品
	 */
	public function electronic() {
		$Model = M('article_electronic');
		
		$this -> _list( $Model, array(), true );
		
		$this -> display();
	}
	
	/**
	 * 计算机网络
	 */
	public function network() {
		$Model = M('article_network');
		
		$this -> _list( $Model, array(), true );
		$this -> display();
	}
	
	/**
	 * 资讯
	 */
	public function news() {
		$Model = M('article_news');
		
		$this -> _list( $Model, array(), true );
		$this -> display();
	}
	
	/**
	 * 程序
	 */
	public function program() {
		$Model = M('article_program');
		$this -> _list( $Model, array(), true );
		
		$this -> display();
	}
	
	/**
	 * 汽车
	 */
	public function car() {
		$Model = M('article_car');
		$this -> _list( $Model, array(), true );
		
		$this -> display();
	}
	
	/**
	 * 扩展字段
	 * @see CommonAction::outputExt()
	 */
	protected function outputExt($list) {
		if ($list) {
			$categoryList = D('Article', 'Logic') -> getAllCategory();
			$category = array();
			if ($categoryList) {
				foreach ($categoryList as $val) {
					$category[$val['id']] = $val['name'];
				}
			}
			
			foreach ($list as $key => $val) {
				$val['category'] = $category[$val['category_id']];
				$val['create_time'] = ($val['create_time'] > 0) ? date('Y-m-d H:i:s', $val['create_time']) : '';
				$val['update_time'] = ($val['update_time'] > 0) ? date('Y-m-d H:i:s', $val['update_time']) : '';
				
				$list[$key] = $val;
			}
		}
		
		return $list;
	}
	
	/**
	 * 更新状态
	 */
	public function updateStatus() {
		$table = trim($_GET['table']);
		$id = intval($_GET['id']);
		$status = intval($_GET['status']);
		
		if (!$table || !$id || !isset($status))
			$this -> alertError('参数错误！');
		
		$newStatus = ($status==1) ? 0 : 1;
		$Model = D('article_'.$table);
		$record = $Model -> where('id='.$id) -> find();
		if (!$record)
			$this -> alertWarn('记录不存在或者已经被删除！');

		if ($record['status'] != $newStatus) {
			$ret = $Model -> where('id='.$id.' AND status='.$status) -> save(array('status'=>$newStatus));
			if (!$ret)
				$this -> alertError('修改状态失败！');
		}
			
		$this -> success('修改状态成功！');
	}
	
	
	/**
	 * 获取某条记录
	 * @param integer $id 记录ID
	 * @param string $table 表名
	 */
	protected function getArticleById( $id, $table, $field='*' ) {
		$Model = D($table);
		if (empty($Model))
			$this -> error('模型对象不存在！');
		
		$sql = 'id='.$id;
		$record = $Model -> field($field)
			-> where($sql)
			->find();
		
		$record['create_time'] = date('Y-m-d H:i:s', $record['create_time']);
		
		return $record;
	}
	
	
	
}